package com. easyj.base.security.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.easyj.admin.sys.service.UserService;
import com.easyj.base.security.OnlineUser;
import com.easyj.base.security.SimpleUser;
import com.easyj.base.security.UserAuthorities;
import com.easyj.base.security.service.JCacheSecurityService;
import com.easyj.base.security.service.TokenUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class JCacheAuthenticationTokenFilter extends OncePerRequestFilter {
   /**
    *     组装认证信息，放到SecurityContextHolder
    */

	@Autowired 
	private  JCacheSecurityService cacheSecurityService;
	
	@Autowired
	private  UserService userService;
	
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //get user
        OnlineUser onlineUser = null;
        
    	String token = TokenUtil.getToken(request); 
    	if(token!=null) {
    		onlineUser = cacheSecurityService.getOnlineUser(token);                       
    	}
        
        if (onlineUser != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        	//get permissions  cache
    		UserAuthorities  permissions=userService.getUserAuthoritiesByCache(onlineUser.getId(),onlineUser.getDepartmentId());
        	
    		/**
        	 * 这里设置authentication，把simpleuUser 的username   值设为用户ID 
        	 * activiti 要取当前authenticatedUserId 从 SecurityContextHolder.getContext().getAuthentication.getName() 得到
        	 * 这里使用用户Id(不使用账号)作为activiti的authenticatedUserId
        	 */
        	SimpleUser simpleUser=new  SimpleUser(onlineUser.getId(),onlineUser.getDepartmentId(),onlineUser.getName(),onlineUser.getId().toString(),onlineUser.getLoginName(),permissions.getAuthorities());
            
        	
        	UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(simpleUser, null, simpleUser.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            //设置当前 activiti用户ID 为登录用户的ID----------
            org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(simpleUser.getId()+"");
        }
        chain.doFilter(request, response);
    }
}
